<template>
    <div>
        <el-dialog
            :title="`设置角色权限 【${role?role.name:''}】`"
            :visible.sync="visible"
            :close-on-click-modal="false">

            <!-- 表格 -->
            <el-table
                ref="table"
                size="medium"
                empty-text="暂无数据"
                element-loading-text="给我一点时间"
                fit border highlight-current-row
                default-expand-all
                height="550"
                row-key="id"
                :indent="30"
                v-loading="loading"
                :data="tree"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}">

                <el-table-column label="名称" prop="name" align="left" show-overflow-tooltip width="250"/>

                <el-table-column label="权限" align="left">
                    <template slot-scope="scope" v-if="scope.row.permission">

                        <el-checkbox-group v-model="permissionCheckList">
                            <el-checkbox :label="'checkAll-'+scope.row.id" @change="handleCheckAllChange">全选</el-checkbox>
                            <el-checkbox v-for="item in scope.row.permission"
                                :label="`${scope.row.id}-${item.id}`"
                                :key="`${scope.row.id}-${item.id}`">
                                {{ item.name }}
                            </el-checkbox>
                        </el-checkbox-group>

                    </template>
                </el-table-column>

            </el-table>


            <div slot="footer" class="dialog-footer">
                <el-button @click="visible = false">取 消</el-button>
                <el-button :icon="!toggleCheck?'el-icon-check':'el-icon-close'" @click="handleCheckAll" size="medium">{{!toggleCheck?'全选':'不选'}}</el-button>
                <el-button @click="handleSubmit()" type="primary" :submitLoading="submitLoading">提 交</el-button>
            </div>

        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            visible: false,
            submitLoading: false,
            loading: false,
            tree: [],
            toggleCheck: false,
            allPermissionList: [],      // 所有的权限
            permissionCheckList: [],    // 选中的权限
            role: null
        }
    },

    mounted() {
        this.$nextTick(() => {

        })
    },

    methods: {
        init(role) {
            const refs = this.$refs
            this.visible = true
            this.$nextTick(() => {
                this.role = role
                this.getListWithTree()
            })
        },

        /**
         * 详细信息
         */
        async getInfo(id) {
            if (id) {
                const res = await this.$http({
                    url: '/system/sysrole/info/' + id,
                    method: 'GET'
                })
                this.form = Object.assign({}, res.data)
            }
        },

        /**
         * 获取表格数据
         */
        async getListWithTree() {
            this.loading = true

            // 加载菜单
            const res = await this.$http({
                url: '/system/sysmenu/listWithTreeOnPermission',
                method: 'GET'
            })
            if (this.ResultMessage(res, false)) {
                this.tree = res.data
            }

            // 加载所有权限
            const resPermits = await this.$http({
                url: '/system/syspermission/list',
                method: 'GET'
            })
            if (this.ResultMessage(resPermits, false)) {
                this.allPermissionList = resPermits.data
            }

            // 根据角色ID获取对应的权限
            const resRolePermit = await this.$http({
                url: '/system/sysrole/getPermissionByRoleId/'+this.role.id,
                method: 'GET'
            })
            if (this.ResultMessage(resRolePermit, false)) {
                this.permissionCheckList = []
                if(resRolePermit.data) {
                    for(let item of resRolePermit.data) {
                        this.permissionCheckList.push(item.menuId+'-'+item.permissionId)
                    }
                }
            }
            this.loading = false
        },

        /**
         * 提交表单
         */
        async handleSubmit() {
            const refs = this.$refs
            this.submitLoading = true
            this.handleFilterPermission();
            let data = {"roleId": this.role.id, "permissions": this.permissionCheckList}
            const res = await this.$http({
                url: `/system/sysrole/saveRolePermission`,
                method: 'POST',
                data
            })
            if (this.ResultMessage(res)) {
                this.submitLoading = false
                this.visible = false
            } else {
                this.submitLoading = false
            }
        },

        /**
         * 全部全选
         */
        handleCheckAll() {
            if(!this.toggleCheck) {
                this.permissionCheckList = []
                for(let item of this.allPermissionList) {
                    this.permissionCheckList.push(item.menuId+'-'+item.id)
                }
            } else {
                this.permissionCheckList = []
            }
            this.toggleCheck = !this.toggleCheck
        },

        /**
         * 全选
         */
        handleCheckAllChange(checked, e) {
            const menuId = e.target.getAttribute('value').split("-")[1]

            //获取当前选中菜单的权限
            let nodePermissions = this.getMenuNodePermission(menuId)

            if(checked) { //全选
                let permissions = []
                for(let item of nodePermissions) {
                    permissions.push(menuId+'-'+item.id)
                }
                //将当前选中的权限与已选的权限去重
                this.permissionCheckList = Array.from(new Set([...this.permissionCheckList, ...permissions]))
            } else { // 全不选
                let tempPermission = []
                for (let item of nodePermissions) {
                    tempPermission.push(menuId+'-'+item.id)
                }
                for (let item of tempPermission) {
                    //获取索引
                    let index = this.permissionCheckList.findIndex(function (val) {
                        return val == item
                    })
                    if (index != -1) {
                        //删除元素
                        this.permissionCheckList.splice(index, 1)
                    }
                }
            }
        },

        /**
         * 根据菜单ID获取对应的权限
         */
        getMenuNodePermission(menuId) {
            let nodePermission = this.allPermissionList.filter(function (item, index, array) {
                return item.menuId == menuId
            })
            return nodePermission
        },

        /**
         * 找出全选复选框的索引，删除
         */
        handleFilterPermission() {
            let count = 0;
            for(let item of this.permissionCheckList) {
                const split = item.split('-')
                if(split[0] === 'checkAll') {
                    count++;
                }
            }
            for(let i=0; i<count; i++) {
                let index = this.permissionCheckList.findIndex((value, index, arr) => {
                    const split = value.split('-')
                    return split[0] === 'checkAll'
                })
                this.permissionCheckList.splice(index, 1)
            }
        }

    }
};
</script>

<style lang="scss" scoped>

</style>
